package com_.dxy_test_.nio_.socket_;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @ClassName: NioClient
 * @Description: Nio客户端
 * @Author: dangxianyue
 * @Date: 2022/05/15 11:40:45
 * @Version: V1.0
 **/
public class NioClient {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);// 非阻塞
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 6666));
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        while(true) {
            selector.select(1000);
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectedKeys.iterator();
            SelectionKey key = null;
            while(iterator.hasNext()) {
                key = iterator.next();
                if(key.isConnectable()) {
                    try {
                        SocketChannel clientChannel = (SocketChannel) key.channel();
                        if (clientChannel.isConnectionPending()){
                            clientChannel.finishConnect();
                        }
                        clientChannel.configureBlocking(false);
                        String info = "服务端你好!!";
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        byteBuffer.put(info.getBytes());
                        byteBuffer.flip();
                        clientChannel.write(byteBuffer);
                        clientChannel.register(key.selector(),SelectionKey.OP_READ);
                    }catch(IOException e) {e.printStackTrace();}
                } else if(key.isReadable()) {
                    try {
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        SocketChannel clientChannel = (SocketChannel) key.channel();
                        int readBytes = clientChannel.read(buffer);//这里position已经变化
                        if (readBytes > 0) {
                            // =====取出buffer里的数据
                            buffer.flip();//position重置为0，为下面的remaining准备
                            byte[] bytes = new byte[buffer.remaining()]; // 创建字节数组
                            buffer.get(bytes);// 将数据取出放到字节数组里
                            String content = new String(bytes);
                            System.out.println("**收到服务端数据包:" + content);
                        }

                    }catch(IOException e) {e.printStackTrace();}
                }
                iterator.remove();// 必须要有，不然下次轮询又会出现该SelectionKey对象
            }
        }
    }
}
